package com.weilian.ordering;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.weilian.ordering.beans.PageBean;
import com.weilian.ordering.beans.TypeBean;
import com.weilian.ordering.common.GloableData;
import com.weilian.ordering.common.PageControl;
import com.weilian.ordering.common.Preferences;
import com.weilian.ordering.util.Logger;
import com.weilian.ordering.view.ScreenSaveDialog;

public class MainMenuActivity extends Activity {
	private final Logger log = Logger.getLogger(getClass());
	private ArrayList<TypeBean> list = new ArrayList<TypeBean>();
	private ArrayList<Button> typeBtnList = new ArrayList<Button>();
	private LinearLayout typeLinearLayout;
	private ViewFlipper tipsFlipper;
	private ViewFlipper flipper;
	private long lastTouch = 0;
	private boolean isRun = false;
	private final int screen_timer = 1000 * 10;
	private Broadcast broadcast = null;
	private GestureDetector deprecated;
	private PageControl pageControl;
	private Handler mHandler;
	private Preferences p;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		tipsFlipper = (ViewFlipper) findViewById(R.id.tipsFlipper);
		tipsFlipper.setInAnimation(AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.push_up_in));
		tipsFlipper.setOutAnimation(AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.push_up_out));
		flipper = (ViewFlipper) findViewById(R.id.viewflow);
		typeLinearLayout = (LinearLayout) findViewById(R.id.typelist_linearlayou);
		p = Preferences.getInstance(this);
		loadTypes();
		if (list.size() > 0) {
			pageControl = new PageControl(flipper, list.get(0), this, handler);
			deprecated = new GestureDetector(pageControl);
			mHandler = pageControl.getHandler();
			changeTypeButtonStyle(list.get(0).typeName);
			// 启动提示
			startTips();
			// 添加接收广播事件
			broadcast = new Broadcast();
			IntentFilter filter = new IntentFilter(GloableData.SCREEN_ACTION);
			this.registerReceiver(broadcast, filter);
			// 启动监听的server
			Intent service = new Intent(MainMenuActivity.this,
					ScreenSaveService.class);
			startService(service);
		} else {
			new AlertDialog.Builder(this).setTitle("提示").setMessage(
					"无菜单数据，请先按格式添加！").setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							finish();
						}
					}).show();
		}
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isRun = false;
		lastTouch = System.currentTimeMillis();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Intent service = new Intent(MainMenuActivity.this,
				ScreenSaveService.class);
		stopService(service);
		if (broadcast != null)
			this.unregisterReceiver(broadcast);

	};

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				checkTime();
				break;
			case 1000:
				errorDialog();
				break;
			}
		};
	};

	private void loadTypes() {
		String typePath = GloableData.pictureBasePath + "category/";
		File file = new File(typePath);
		String[] names = file.list();
		for (String s : names) {
			addTypeButton(s);
			TypeBean bean = new TypeBean();
			bean.typeName = s;
			list.add(bean);
		}
		if (list.size() > 0) {
			File content = new File(GloableData.pictureBasePath + "category/"
					+ list.get(0).typeName);
			try {
				String[] lists = content.list();

				if (lists != null && lists.length > 0) {

					for (String path : lists) {
						PageBean bean = new PageBean();
						bean.imagePath = GloableData.pictureBasePath
								+ "category/" + list.get(0).typeName + "/"
								+ path;
						list.get(0).list.add(bean);
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(e.toString());
				log.e(e);
				handler.sendEmptyMessage(1000);
			}
		}
	}
	
	private void errorDialog(){
		Builder dialog = new Builder(this);
		dialog.setMessage("提示");
		dialog.setMessage("菜品图片读取错误，请先检查文件格式！");
		dialog.setNegativeButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		dialog.show();
		
	}

	private void addTypeButton(String tip) {
		Button btn = new Button(getApplicationContext());
		btn.setText(tip);
		btn.setTextSize(25);
		btn.setPadding(5, 5, 5, 10);
		btn.setWidth(50);
		btn.setTextColor(getResources().getColor(R.color.white));
		btn.setBackgroundResource(R.drawable.type);
		btn.setOnClickListener(new TypeOnClickListener(tip));
		typeBtnList.add(btn);
		typeLinearLayout.addView(btn);
	}

	class TypeOnClickListener implements OnClickListener {
		String typeName;

		public TypeOnClickListener(String typeName) {
			// TODO Auto-generated constructor stub
			this.typeName = typeName;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			lastTouch = System.currentTimeMillis();
			changeType(typeName);
		}

	}

	private int changeTypeButtonStyle(String typeName) {
		int position = 0;
		for (Button btn : typeBtnList) {
			if (!btn.getText().equals(typeName)) {
				btn.setBackgroundResource(R.drawable.type);
				btn.setTextColor(getResources().getColor(R.color.white));
			} else {
				btn.setBackgroundResource(R.drawable.type_sel);
				btn.setTextColor(getResources().getColor(R.color.brown));
				position = typeBtnList.indexOf(btn);
			}
		}
		return position;
	}

	private void changeType(String typeName) {
		int position = changeTypeButtonStyle(typeName);
		TypeBean bean = list.get(position);
		if (bean.list.size() == 0) {
			File file = new File(GloableData.pictureBasePath + "category/"
					+ bean.typeName + "/");
			String[] names = file.list();
			for (String name : names) {
				PageBean page = new PageBean();
				page.imagePath = GloableData.pictureBasePath + "category/"
						+ bean.typeName + "/" + name;
				bean.list.add(page);
			}
		}
		Message msg = new Message();
		msg.what = 0;
		msg.obj = bean;
		mHandler.sendMessage(msg);
	}
	
	//设置Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, "幻灯时间");
		menu.add(0, 1, 0, "退出");
		return super.onCreateOptionsMenu(menu);
	} 
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			ScreenSaveDialog dialog =new ScreenSaveDialog(this);
			dialog.showDialog();
			break;
		case 1:
			exitDialog();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 设置text滚动
	private void initScollTips(ArrayList<String> list) {
		// TODO Auto-generated method stub
		tipsFlipper.removeAllViews();
		for (final String tips : list) {
			TextView textView = new TextView(getApplicationContext());
			textView.setSingleLine(true);
			textView.setTextColor(getResources().getColor(R.color.red));
			textView.setEllipsize(TextUtils.TruncateAt.END);
			textView.setText(tips);
			textView.setGravity(Gravity.CENTER);
			tipsFlipper.addView(textView);
		}
		tipsFlipper.setFlipInterval(3000);
		tipsFlipper.startFlipping();
	}

	// 获取tips 数据
	private void startTips() {
		ArrayList<String> list = new ArrayList<String>();
		try {
			File tipsFile = new File(GloableData.pictureBasePath + "tip.txt");
			if (tipsFile.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(tipsFile), "UTF-8");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {
					list.add(line);
				}
				read.close();
				reader.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (list.size() == 0) {
			list.add("欢迎光临！");
		}
		initScollTips(list);
	}

	public void exitDialog() {
		isRun = true;
		Builder builder = new Builder(this);
		builder.setMessage("确定要退出吗？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				finish();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				isRun = false;
				dialog.dismiss();
			}
		});
		builder.show();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		exitDialog();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		lastTouch = System.currentTimeMillis();
		return this.deprecated.onTouchEvent(event);
	}

	private void checkTime() {
		long currentTimer = System.currentTimeMillis();
		if (!isRun && currentTimer - lastTouch > p.getScreenSave()*1000) {
			isRun = true;
			Intent intent = new Intent(MainMenuActivity.this,
					ScreenSaverActivity.class);
			startActivity(intent);
		}
	}

	class Broadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(GloableData.SCREEN_ACTION)) {
				log.i("send Service");
				handler.sendEmptyMessage(0);
			}
		}

	}
}
